<script setup>
import { searchUserByUserName } from '@/api/user';
import { computed, onMounted, ref } from 'vue';
import robotSvg from '@/assets/svg/robot.svg';
import { useContactsStore, useUserStore } from '@/stores/counter';
import addUserIcon from '@/assets/svg/add_user.svg';
import { applyFriend } from '@/api/contacts';
import { useRouter } from 'vue-router';
const messages = ref(
    [
        {
            id: 1,
            profileSrc: 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/3364143/download+%281%29.png',
            username: '联系人测试1',
            message: 'What time was our meet',
            date: '20m'
        },
        {
            id: 2,
            profileSrc: 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/3364143/download+%2812%29.png',
            username: '联系人测试2',
            message: 'Snackwave craft beer raclette, beard kombucha',
            date: '2h'
        }
    ]
)

const dialogVisible = ref(false);
const searchQuery = ref('');
const searchResults = ref([]);

const addFriendDialogVisible = ref(false);
const friendRequestMessage = ref('');
const selectedUserId = ref(null);
const userStore = useUserStore();
const router = useRouter();

const useContacts = useContactsStore();
onMounted(() => {
  // 获取新的朋友数据
  useContacts.getContacts(userStore.userId)
})

const contactList = computed(() => useContacts.contacts)

const openDialog = () => {
    dialogVisible.value = true;
};


const searchUser = async () => {
    // 模拟搜索用户信息
    if (searchQuery.value) {
        const res = await searchUserByUserName(searchQuery.value);
        if (res?.data?.rows) {
            searchResults.value = res.data.rows;
            ElMessage.success('搜索成功');
            return
        }
        ElMessage.error('未搜索到该用户');
    } else {
        ElMessage.error('请输入搜索信息');
    }
};

const openAddFriendDialog = (userId) => {
    selectedUserId.value = userId;
    friendRequestMessage.value = '';
    addFriendDialogVisible.value = true;
};

const sendFriendRequest = async () => {
    const friendRequest = {
        uid: userStore.userId,
        targetId: selectedUserId.value,
        msg: friendRequestMessage.value,
        type: 1
    };
    // 发送好友申请逻辑
    const res = await applyFriend(friendRequest);
    console.log('发送好友申请:', friendRequest);
    addFriendDialogVisible.value = false;
    ElMessage.success('好友申请已发送');
};

const handleCancel = () => {
    searchQuery.value = '';
    friendRequestMessage.value = '';
    dialogVisible.value = false;
    addFriendDialogVisible.value = false;
    searchResults.value = [];
    selectedUserId.value = null
};

const goToNewFriends = () => {
  router.push('/newFriend')
}

useContacts.getApplyListCount(userStore.userId);

</script>

<template>
    <div class="conversation-area">
        <div class="new-friend" @click="goToNewFriends">
            <div class="icon-container">
                <img class="msg-profile" :src="addUserIcon" alt="New Friend" />
                <div v-if="useContacts.newFriendCount > 0" class="badge">
                    {{ useContacts.newFriendCount > 99 ? '99+' : useContacts.newFriendCount }}
                </div>
            </div>
            <div class="msg-detail">
                <div class="msg-username">新的朋友</div>
            </div>
        </div>
        <div class="msg online" v-for="contact in contactList" :key="contact.id">
            <img class="msg-profile" :src="contact.avatar || robotSvg" alt="" />
            <div class="msg-detail">
                <div class="msg-username">{{ contact.userName }}</div>
            </div>
        </div>
        <button class="add" @click="openDialog"></button>
        <div class="overlay"></div>
    </div>

    <el-dialog title="添加好友" width="25%" v-model="dialogVisible" draggable @close="handleCancel">
        <div class="search-bar">
            <el-input v-model="searchQuery" placeholder="请输入用户账号"></el-input>
            <el-button type="primary" @click="searchUser">搜索</el-button>
        </div>
        <div v-if="searchResults.length">
            <div v-for="result in searchResults" :key="result.userId" class="search-result">
                <img :src="result.avatar || robotSvg" alt="" class="result-profile" />
                <div class="result-detail">
                    <div class="result-username">{{ result.name }}</div>
                </div>
                <el-button type="primary" @click="openAddFriendDialog(result.userId)">添加</el-button>
            </div>
        </div>
    </el-dialog>

    <el-dialog title="好友申请" width="25%" v-model="addFriendDialogVisible" draggable @close="handleCancel">
        <el-form label-width="80px">
            <el-form-item label="申请信息">
                <el-input type="textarea" v-model="friendRequestMessage" placeholder="请输入申请信息"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="sendFriendRequest">确定</el-button>
                <el-button @click="addFriendDialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<style lang="scss" scoped>
.conversation-area {
    border-right: 1px solid var(--border-color);
    overflow-y: auto;
    overflow-x: hidden;
    display: flex;
    flex-direction: column;
    position: relative;
    height: 100%;
}

.conversation-area,
.detail-area {
    width: 340px;
    flex-shrink: 0;
}

@media (max-width: 780px) {
    .conversation-area {
        display: none;
    }

    .search-bar {
        margin-left: 0;
        flex-grow: 1;

        input {
            padding-right: 10px;
        }
    }
}

.msg-profile {
    width: 44px;
    height: 44px;
    border-radius: 50%;
    object-fit: cover;
    margin-right: 15px;

    &.group {
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: var(--border-color);

        svg {
            width: 60%;
        }
    }
}

.msg {
    display: flex;
    align-items: center;
    padding: 20px;
    cursor: pointer;
    transition: 0.2s;
    position: relative;

    &:hover {
        background-color: var(--msg-hover-bg);
    }

    &.active {
        background: var(--active-conversation-bg);
        border-left: 4px solid var(--theme-color);
    }

    &.online:before {
        content: "";
        position: absolute;
        background-color: #23be7e;
        width: 9px;
        height: 9px;
        border-radius: 50%;
        border: 2px solid var(--theme-bg-color);
        left: 50px;
        bottom: 19px;
    }
}

.msg-username {
    margin-bottom: 4px;
    font-weight: 600;
    font-size: 15px;
}

.msg-detail {
    overflow: hidden;
}

.msg-content {
    font-weight: 500;
    font-size: 13px;
    display: flex;
}

.msg-message {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: var(--msg-message);
}

.msg-date {
    font-size: 14px;
    color: var(--msg-date);
    margin-left: 3px;

    &:before {
        content: "•";
        margin-right: 2px;
    }
}

.add {
    position: sticky;
    bottom: 25px;
    background-color: var(--theme-color);
    width: 60px;
    height: 60px;
    border: 0;
    border-radius: 50%;
    background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-plus'%3e%3cpath d='M12 5v14M5 12h14'/%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: 50%;
    background-size: 28px;
    box-shadow: 0 0 16px var(--theme-color);
    margin: auto auto -55px;
    flex-shrink: 0;
    z-index: 1;
    cursor: pointer;
}

.overlay {
    position: sticky;
    bottom: 0;
    left: 0;
    width: 340px;
    flex-shrink: 0;
    background: var(--overlay-bg);
    height: 80px;
}

.search-bar {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;
}

.search-result {
    display: flex;
    align-items: center;
    margin-top: 10px;
}

.result-profile {
    width: 44px;
    height: 44px;
    border-radius: 50%;
    margin-right: 10px;
}

.result-detail {
    flex-grow: 1;
}

.result-username {
    font-weight: bold;
}

.new-friend {
    display: flex;
    align-items: center;
    padding: 20px;
    cursor: pointer;
    transition: 0.2s;
    position: relative;

    &:hover {
        background-color: var(--msg-hover-bg);
    }

    .msg-profile {
        width: 44px;
        height: 44px;
        border-radius: 50%;
        margin-right: 15px;
    }

    .msg-detail {
        flex-grow: 1;
    }

    .msg-username {
        font-weight: 600;
        font-size: 15px;
    }
}

.new-friend .icon-container {
  position: relative;
  display: inline-block;
}

.new-friend img {
  width: 50px; 
  height: 50px; 
}

.badge {
  position: absolute;
  top: -5px;
  right: 5px;
  background-color: red;
  color: white;
  border-radius: 50%;
  padding: 2px 6px;
  font-size: 12px;
  font-weight: bold;
}
</style>